/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.support;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.core.SimpleAliasRegistry;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * {@link SingletonBeanRegistry}的实现类.
 * <p>
 * Generic registry for shared bean instances, implementing the
 * {@link org.springframework.beans.factory.config.SingletonBeanRegistry}.
 * Allows for registering singleton instances that should be shared
 * for all callers of the registry, to be obtained via bean name.
 * <p>
 * <p>Also supports registration of
 * {@link org.springframework.beans.factory.DisposableBean} instances,
 * (which might or might not correspond to registered singletons),
 * to be destroyed on shutdown of the registry. Dependencies between
 * beans can be registered to enforce an appropriate shutdown order.
 * <p>
 * <p>This class mainly serves as base class for
 * {@link org.springframework.beans.factory.BeanFactory} implementations,
 * factoring out the common management of singleton bean instances. Note that
 * the {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
 * interface extends the {@link SingletonBeanRegistry} interface.
 * <p>
 * <p>Note that this class assumes neither a bean definition concept
 * nor a specific creation process for bean instances, in contrast to
 * {@link AbstractBeanFactory} and {@link DefaultListableBeanFactory}
 * (which inherit from it). Can alternatively also be used as a nested
 * helper to delegate to.
 *
 * @author Juergen Hoeller
 * @see #registerSingleton
 * @see #registerDisposableBean
 * @see org.springframework.beans.factory.DisposableBean
 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory
 * @since 2.0
 */
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {

	/**
	 * Logger available to subclasses
	 */
	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * 存放单例对象的缓存
	 * Cache of singleton objects: bean name --> bean instance
	 */
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	/**
	 * 存放制造单例对象的缓存
	 * Cache of singleton factories: bean name --> ObjectFactory
	 */
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

	/**
	 * 存放通过单例工厂制造出来的单例对象的缓存，这里存放的对象此时并不一定已经被实例化了。
	 * Cache of early singleton objects: bean name --> bean instance
	 */
	private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

	/**
	 * 注册的单例类集合,包含了注册顺序.也就是单例注册表.
	 * <p>
	 * Set of registered singletons, containing the bean names in registration order
	 */
	private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

	/**
	 * 当前正在创建的单例对象的名称集合.
	 * <p>
	 * Names of beans that are currently in creation
	 */
	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	/**
	 * 在创建过程中检查当前排除的bean名称.
	 * <p>
	 * Names of beans currently excluded from in creation checks
	 */
	private final Set<String> inCreationCheckExclusions =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	/**
	 * 被抑制的异常列表,可以有效的关联相关的原因.
	 * <p>
	 * List of suppressed Exceptions, available for associating related causes
	 */
	@Nullable
	private Set<Exception> suppressedExceptions;

	/**
	 * 正在销毁单例对象的标志
	 * Flag that indicates whether we're currently within destroySingletons
	 */
	private boolean singletonsCurrentlyInDestruction = false;

	/**
	 * 一次性bean实例缓存:bean名称-->bean实例
	 * <p>
	 * Disposable bean instances: bean name --> disposable instance
	 */
	private final Map<String, Object> disposableBeans = new LinkedHashMap<>();

	/**
	 * 嵌入式bean名称之间的映射:bean名称-->内部bean名称
	 * <p>
	 * Map between containing bean names: bean name --> Set of bean names that the bean contains
	 */
	private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);

	/**
	 * 依赖bean映射:bean名称-->依赖该bean的bean名称集合  a有个属性为b,那么就是b-->a
	 * <p>
	 * Map between dependent bean names: bean name --> Set of dependent bean names
	 */
	private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);

	/**
	 * 依赖bean映射"bean名称-->bean依赖的bean名称的集合  a有个属性b,那么就是a-->b.
	 * Map between depending bean names: bean name --> Set of bean names for the bean's dependencies
	 */
	private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);

	/**
	 * 注册单例实例
	 *
	 * @param beanName        the name of the bean
	 * @param singletonObject the existing singleton object
	 * @throws IllegalStateException
	 */
	@Override
	public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
		Assert.notNull(beanName, "Bean name must not be null");
		Assert.notNull(singletonObject, "Singleton object must not be null");
		synchronized (this.singletonObjects) {
			//单例实例缓存器中是否包含了该数据,如果包含了指定名称,表示名称已被占用.
			Object oldObject = this.singletonObjects.get(beanName);
			if (oldObject != null) {
				throw new IllegalStateException("Could not register object [" + singletonObject +
						"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
			}
			//名称没有被占用,真正的注册操作.
			addSingleton(beanName, singletonObject);
		}
	}

	/**
	 * 将指定的单例对象添加到当前工厂内.
	 * 并立即注册为单例实例.
	 * <p>
	 * Add the given singleton object to the singleton cache of this factory.
	 * <p>To be called for eager registration of singletons.
	 *
	 * @param beanName        the name of the bean
	 * @param singletonObject the singleton object
	 */
	protected void addSingleton(String beanName, Object singletonObject) {
		synchronized (this.singletonObjects) {
			//添加到单例对象中
			this.singletonObjects.put(beanName, singletonObject);
			//指定名称的单例bean实例已经被存放到了singletonObjects缓存中,所以singletonFactories不再持有指定名称的bean工厂.
			this.singletonFactories.remove(beanName);
			//既然已经通过singletonObjects存放了单例实例,那么earlySingletonObjects就不应该继续持有指定名称的bean.
			this.earlySingletonObjects.remove(beanName);
			//将指定名称的单例类放入到单例注册表中.
			this.registeredSingletons.add(beanName);
		}
	}

	/**
	 * 在需要的时候,通过指定的单例工厂构建一个指定的单例实例并立即实例化.
	 * <p>
	 * Add the given singleton factory for building the specified singleton
	 * if necessary.
	 * <p>To be called for eager registration of singletons, e.g. to be able to
	 * resolve circular references.
	 *
	 * @param beanName         the name of the bean
	 * @param singletonFactory the factory for the singleton object
	 */
	protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(singletonFactory, "Singleton factory must not be null");
		synchronized (this.singletonObjects) {
			//尚未实例化
			if (!this.singletonObjects.containsKey(beanName)) {
				//单例工厂放入该属性,此时该实例还没有被实例化.
				this.singletonFactories.put(beanName, singletonFactory);
				//从已经注册的单例实例中移除掉.
				this.earlySingletonObjects.remove(beanName);
				//添加到注册表中.
				this.registeredSingletons.add(beanName);
			}
		}
	}

	/**
	 * 获取单例实例,并立即初始化
	 *
	 * @param beanName the name of the bean to look for
	 * @return
	 */
	@Override
	@Nullable
	public Object getSingleton(String beanName) {
		return getSingleton(beanName, true);
	}

	/**
	 * 返回用指定名称注册的单例对象.
	 * 检查已经创建的单例对象和允许提前对单例对象进行引用(解决循环引用).
	 * <p>
	 * Return the (raw) singleton object registered under the given name.
	 * <p>Checks already instantiated singletons and also allows for an early
	 * reference to a currently created singleton (resolving a circular reference).
	 *
	 * @param beanName            the name of the bean to look for
	 * @param allowEarlyReference whether early references should be created or not 是否允许在Bean定义加载完成前提前引用。
	 *                            换句话说，是否允许引用尚未初始化的bean实例。
	 * @return the registered singleton object, or {@code null} if none found
	 */
	@Nullable
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
		//从单例实例缓存器中获取单例对象
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			//当前单例对象为null,同时该单例对象正在被创建中...
			synchronized (this.singletonObjects) {
				singletonObject = this.earlySingletonObjects.get(beanName);
				//当前实例对象没有被创建完毕,同时允许立即进行引用...
				if (singletonObject == null && allowEarlyReference) {
					//获取该对象的单例工厂
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
						//获取该工厂生产的对象
						singletonObject = singletonFactory.getObject();
						//存放入已经加载的单例缓存中
						this.earlySingletonObjects.put(beanName, singletonObject);
						//移除掉该单例对应的工厂
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		//如果指定对象并没有正在创建,或者对象不允许预先引用,这里就会返回一个null.
		return singletonObject;
	}

	/**
	 * 返回通过指定名称的原始单例对象.如果没有注册,就创建并注册一个.
	 * <p>
	 * Return the (raw) singleton object registered under the given name,
	 * creating and registering a new one if none registered yet.
	 *
	 * @param beanName         the name of the bean
	 * @param singletonFactory the ObjectFactory to lazily create the singleton
	 *                         with, if necessary
	 * @return the registered singleton object
	 */
	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(beanName, "Bean name must not be null");
		synchronized (this.singletonObjects) {
			//从当前的单例实例缓存中获取指定名称的饿单例bean.
			Object singletonObject = this.singletonObjects.get(beanName);

			if (singletonObject == null) {
				//如果不存在单例实例.
				if (this.singletonsCurrentlyInDestruction) {
					//正在销毁单例实例
					throw new BeanCreationNotAllowedException(beanName,
							"Singleton bean creation not allowed while singletons of this factory are in destruction " +
									"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
				}
				//执行创建前的检查,主要是为了排除循环依赖.
				beforeSingletonCreation(beanName);
				boolean newSingleton = false;
				boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
				if (recordSuppressedExceptions) {
					//不存在抑制的异常,新建一个.
					this.suppressedExceptions = new LinkedHashSet<>();
				}
				try {
					//尝试从单例工厂构建一个单例对象.
					singletonObject = singletonFactory.getObject();

					newSingleton = true;//新建单例成功.
				} catch (IllegalStateException ex) {
					// Has the singleton object implicitly appeared in the meantime ->
					// if yes, proceed with it since the exception indicates that state.
					//隐式出现了异常
					singletonObject = this.singletonObjects.get(beanName);
					if (singletonObject == null) {
						throw ex;
					}
				} catch (BeanCreationException ex) {
					if (recordSuppressedExceptions) {
						for (Exception suppressedException : this.suppressedExceptions) {
							ex.addRelatedCause(suppressedException);
						}
					}
					throw ex;
				} finally {
					if (recordSuppressedExceptions) {
						this.suppressedExceptions = null;
					}
					//创建单例对象的后置处理
					afterSingletonCreation(beanName);
				}
				if (newSingleton) {
					//注册单例实例
					addSingleton(beanName, singletonObject);
				}
			}
			return singletonObject;
		}
	}

	/**
	 * 注册发生在单例bean实例创建过程中的异常.
	 * <p>
	 * Register an Exception that happened to get suppressed during the creation of a
	 * singleton bean instance, e.g. a temporary circular reference resolution problem.
	 *
	 * @param ex the Exception to register
	 */
	protected void onSuppressedException(Exception ex) {
		synchronized (this.singletonObjects) {
			if (this.suppressedExceptions != null) {
				this.suppressedExceptions.add(ex);
			}
		}
	}

	/**
	 * 从当前工厂的单例缓存中移除掉指定名称的bean,以便能够在创建失败的时候清除掉单例的立即注册属性.
	 * <p>
	 * Remove the bean with the given name from the singleton cache of this factory,
	 * to be able to clean up eager registration of a singleton if creation failed.
	 *
	 * @param beanName the name of the bean
	 * @see #getSingletonMutex()
	 */
	protected void removeSingleton(String beanName) {
		synchronized (this.singletonObjects) {
			//从单例实例缓存器中移除该实例.
			this.singletonObjects.remove(beanName);
			//从工厂中移除.
			this.singletonFactories.remove(beanName);
			//移除掉已加载状态
			this.earlySingletonObjects.remove(beanName);
			//从已注册状态移除
			this.registeredSingletons.remove(beanName);
		}
	}

	/**
	 * 是否已经缓存了当前单例
	 *
	 * @param beanName the name of the bean to look for
	 * @return
	 */
	@Override
	public boolean containsSingleton(String beanName) {
		return this.singletonObjects.containsKey(beanName);
	}

	/**
	 * 获取所有已经注册的单例对象的名称集合
	 *
	 * @return
	 */
	@Override
	public String[] getSingletonNames() {
		synchronized (this.singletonObjects) {
			return StringUtils.toStringArray(this.registeredSingletons);
		}
	}

	/**
	 * 获取已经注册了的单例数量.
	 *
	 * @return
	 */
	@Override
	public int getSingletonCount() {
		synchronized (this.singletonObjects) {
			return this.registeredSingletons.size();
		}
	}

	/**
	 * 设置当前正在创建中的状态.
	 *
	 * @param beanName
	 * @param inCreation
	 */
	public void setCurrentlyInCreation(String beanName, boolean inCreation) {
		Assert.notNull(beanName, "Bean name must not be null");
		if (!inCreation) {
			//当前不是正在缓存,将其设置为排除检查.
			this.inCreationCheckExclusions.add(beanName);
		} else {
			//当前正在创建过程中,将其从排除列表中移除.
			this.inCreationCheckExclusions.remove(beanName);
		}
	}

	/**
	 * 当前是否正在创建过程中.
	 *
	 * @param beanName
	 * @return
	 */
	public boolean isCurrentlyInCreation(String beanName) {
		Assert.notNull(beanName, "Bean name must not be null");
		return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
	}

	/**
	 * 正在创建中
	 *
	 * @param beanName
	 * @return
	 */
	protected boolean isActuallyInCreation(String beanName) {
		return isSingletonCurrentlyInCreation(beanName);
	}

	/**
	 * 返回指定的单例bean是否正在被创建.
	 * <p>
	 * Return whether the specified singleton bean is currently in creation
	 * (within the entire factory).
	 *
	 * @param beanName the name of the bean
	 */
	public boolean isSingletonCurrentlyInCreation(String beanName) {
		return this.singletonsCurrentlyInCreation.contains(beanName);
	}

	/**
	 * 在创建单例实例之前调用,默认实现了在创建时注册当前的单例.
	 * <p>
	 * Callback before singleton creation.
	 * <p>The default implementation register the singleton as currently in creation.
	 *
	 * @param beanName the name of the singleton about to be created
	 * @see #isSingletonCurrentlyInCreation
	 */
	protected void beforeSingletonCreation(String beanName) {
		//当前的bean名称不在排除列表中,同时当前正在创建该实例.
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}
	}

	/**
	 * 单例对象创建的后置回调,主要是标记单例实例不再处于创建状态.
	 * Callback after singleton creation.
	 * <p>The default implementation marks the singleton as not in creation anymore.
	 *
	 * @param beanName the name of the singleton that has been created
	 * @see #isSingletonCurrentlyInCreation
	 */
	protected void afterSingletonCreation(String beanName) {
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
			throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
		}
	}


	/**
	 * 在当前工厂中注册一个一次性的bean.
	 * 一次性的bean通常应用于注册的单例,bean名称一致但是拥有不同的实例,比如:一个一次性的非正常实现的单例适配器不会实spring的一次性bean接口.
	 * <p>
	 * Add the given bean to the list of disposable beans in this registry.
	 * <p>Disposable beans usually correspond to registered singletons,
	 * matching the bean name but potentially being a different instance
	 * (for example, a DisposableBean adapter for a singleton that does not
	 * naturally implement Spring's DisposableBean interface).
	 *
	 * @param beanName the name of the bean
	 * @param bean     the bean instance
	 */
	public void registerDisposableBean(String beanName, DisposableBean bean) {
		synchronized (this.disposableBeans) {
			this.disposableBeans.put(beanName, bean);
		}
	}

	/**
	 * 注册两个bean之间的包含关系,比如:一个内部bean和一个外部bean.还根据销毁顺序将包含的bean注册为依赖于包含的bean.
	 * <p>
	 * <p>
	 * Register a containment relationship between two beans,
	 * e.g. between an inner bean and its containing outer bean.
	 * <p>Also registers the containing bean as dependent on the contained bean
	 * in terms of destruction order.
	 *
	 * @param containedBeanName  the name of the contained (inner) bean
	 * @param containingBeanName the name of the containing (outer) bean
	 * @see #registerDependentBean
	 */
	public void registerContainedBean(String containedBeanName, String containingBeanName) {
		//一个避免同步冲突的快速检查...
		// A quick check for an existing entry upfront, avoiding synchronization...
		Set<String> containedBeans = this.containedBeanMap.get(containingBeanName);

		if (containedBeans != null && containedBeans.contains(containedBeanName)) {
			//是否已有映射
			return;
		}
		//尚未仅需同步方法.
		// No entry yet -> fully synchronized manipulation of the containedBeans Set
		synchronized (this.containedBeanMap) {
			//再次获取其包含的内部bean集合
			containedBeans = this.containedBeanMap.get(containingBeanName);
			if (containedBeans == null) {
				containedBeans = new LinkedHashSet<>(8);
				this.containedBeanMap.put(containingBeanName, containedBeans);
			}//放入内部bean缓存中
			containedBeans.add(containedBeanName);
		}
		//注册依赖bean
		registerDependentBean(containedBeanName, containingBeanName);
	}

	/**
	 * 注册指定bean的依赖bean.在给定的bean销毁之前销毁.
	 * <p>
	 * Register a dependent bean for the given bean,
	 * to be destroyed before the given bean is destroyed.
	 *
	 * @param beanName          the name of the bean
	 * @param dependentBeanName the name of the dependent bean
	 */
	public void registerDependentBean(String beanName, String dependentBeanName) {
		// A quick check for an existing entry upfront, avoiding synchronization...
		//快速别名检查
		String canonicalName = canonicalName(beanName);
		//获取依赖bean的集合
		Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
		if (dependentBeans != null && dependentBeans.contains(dependentBeanName)) {
			//已经包含了该依赖,跳出
			return;
		}
		// No entry yet -> fully synchronized manipulation of the dependentBeans Set
		synchronized (this.dependentBeanMap) {
			//再次获取依赖.
			dependentBeans = this.dependentBeanMap.get(canonicalName);
			if (dependentBeans == null) {
				dependentBeans = new LinkedHashSet<>(8);
				this.dependentBeanMap.put(canonicalName, dependentBeans);
			}
			//添加到依赖中
			dependentBeans.add(dependentBeanName);
		}
		synchronized (this.dependenciesForBeanMap) {
			//获取被依赖的bean集合.
			Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);
			if (dependenciesForBean == null) {
				dependenciesForBean = new LinkedHashSet<>(8);
				this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);
			}
			//将依赖该bean的bean添加进去
			dependenciesForBean.add(canonicalName);
		}
	}

	/**
	 * 具有传递性的判断是否直接或者间接的依赖某类.
	 * <p>
	 * Determine whether the specified dependent bean has been registered as
	 * dependent on the given bean or on any of its transitive dependencies.
	 *
	 * @param beanName          the name of the bean to check 要检查的bean的名称
	 * @param dependentBeanName the name of the dependent bean 被依赖的bean名称.
	 * @since 4.0
	 */
	protected boolean isDependent(String beanName, String dependentBeanName) {
		return isDependent(beanName, dependentBeanName, null);
	}

	/**
	 * 具有传递性的判断是否直接或者间接的依赖某类.
	 *
	 * @param beanName          要检查的bean的名称
	 * @param dependentBeanName 被依赖的bean名称.
	 * @param alreadySeen       已经处理过的集合
	 * @return
	 */
	private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {

		if (alreadySeen != null && alreadySeen.contains(beanName)) {
			//已经看过的集合中包含要检查的bean,返回false.
			return false;
		}
		//获取到原始的规范的bean名称
		String canonicalName = canonicalName(beanName);
		//获取依赖该bean的bean集合.
		Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);

		if (dependentBeans == null) {
			//没有bean依赖该bean.
			return false;
		}
		if (dependentBeans.contains(dependentBeanName)) {
			//指定bean依赖该bean.
			return true;
		}
		//迭代依赖该bean的bean,继续请求依赖性
		for (String transitiveDependency : dependentBeans) {
			//依赖传递
			if (alreadySeen == null) {
				alreadySeen = new HashSet<>();
			}
			//已经匹配过
			alreadySeen.add(beanName);
			if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
				//判断指定bean依赖的bean是否依赖特定的bean.
				return true;
			}
		}
		return false;
	}

	/**
	 * 确定为指定名称的bean注册了一个依赖项.
	 * <p>
	 * Determine whether a dependent bean has been registered for the given name.
	 *
	 * @param beanName the name of the bean to check
	 */
	protected boolean hasDependentBean(String beanName) {
		return this.dependentBeanMap.containsKey(beanName);
	}

	/**
	 * 返回依赖指定bean的bean名称集合.
	 * <p>
	 * 返回指定名称的bean依赖的bean集合.
	 * Return the names of all beans which depend on the specified bean, if any.
	 *
	 * @param beanName the name of the bean
	 * @return the array of dependent bean names, or an empty array if none
	 */
	public String[] getDependentBeans(String beanName) {
		//获取指定bean依赖的bean集合.
		Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
		if (dependentBeans == null) {
			return new String[0];
		}
		//返回所有依赖的bean集合.
		return StringUtils.toStringArray(dependentBeans);
	}

	/**
	 * 淡灰指定的bean依赖的所有bean名称集合.
	 * <p>
	 * Return the names of all beans that the specified bean depends on, if any.
	 *
	 * @param beanName the name of the bean
	 * @return the array of names of beans which the bean depends on,
	 * or an empty array if none
	 */
	public String[] getDependenciesForBean(String beanName) {
		Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
		if (dependenciesForBean == null) {
			return new String[0];
		}
		return dependenciesForBean.toArray(new String[dependenciesForBean.size()]);
	}

	/**
	 * 销毁单例实例
	 */
	public void destroySingletons() {
		if (logger.isDebugEnabled()) {
			logger.debug("Destroying singletons in " + this);
		}
		synchronized (this.singletonObjects) {

			//销毁状态标志开启
			this.singletonsCurrentlyInDestruction = true;
		}
		/**
		 * 一次性bean名称集合
		 */
		String[] disposableBeanNames;
		synchronized (this.disposableBeans) {
			//获取所有的一次性bean的名称集合.
			disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
		}
		for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
			destroySingleton(disposableBeanNames[i]);
		}
		//内部bean集合.
		this.containedBeanMap.clear();
		//被依赖关系
		this.dependentBeanMap.clear();
		//依赖关系
		this.dependenciesForBeanMap.clear();
		//所有单例bean集合
		synchronized (this.singletonObjects) {
			this.singletonObjects.clear();
			this.singletonFactories.clear();
			this.earlySingletonObjects.clear();
			this.registeredSingletons.clear();
			//移除销毁单例bean标志
			this.singletonsCurrentlyInDestruction = false;
		}
	}

	/**
	 * 销毁指定的bean,如果找到响应的一次性的bean实例,则委托给destroyBean方法来实现.
	 * Destroy the given bean. Delegates to {@code destroyBean}
	 * if a corresponding disposable bean instance is found.
	 *
	 * @param beanName the name of the bean
	 * @see #destroyBean
	 */
	public void destroySingleton(String beanName) {
		//移除指定名称的单例实例
		// Remove a registered singleton of the given name, if any.
		removeSingleton(beanName);
		//销毁对应的一次性bean实例.
		// Destroy the corresponding DisposableBean instance.
		DisposableBean disposableBean;
		synchronized (this.disposableBeans) {
			//移除一次性bean名称
			disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
		}

		destroyBean(beanName, disposableBean);
	}

	/**
	 * 销毁指定的bean实例,必须在销毁该bean之前销毁依赖该bean的bean实例.
	 * Destroy the given bean. Must destroy beans that depend on the given
	 * bean before the bean itself. Should not throw any exceptions.
	 *
	 * @param beanName the name of the bean
	 * @param bean     the bean instance to destroy
	 */
	protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
		//获取依赖该bean的bean集合,并移除掉该bean.
		// Trigger destruction of dependent beans first...
		Set<String> dependencies = this.dependentBeanMap.remove(beanName);
		//递归销毁依赖该bean的bean集合.
		if (dependencies != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
			}
			for (String dependentBeanName : dependencies) {
				destroySingleton(dependentBeanName);
			}
		}
		//真正开始销毁bean.
		// Actually destroy the bean now...
		if (bean != null) {
			try {
				bean.destroy();
			} catch (Throwable ex) {
				logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);
			}
		}
		// 递归销毁他包含的内部bean集合
		// Trigger destruction of contained beans...
		Set<String> containedBeans = this.containedBeanMap.remove(beanName);
		if (containedBeans != null) {
			for (String containedBeanName : containedBeans) {
				destroySingleton(containedBeanName);
			}
		}
		//从其他bean的依赖项中移除该bean.
		// Remove destroyed bean from other beans' dependencies.
		synchronized (this.dependentBeanMap) {
			//获取被依赖关系的所有记录.
			for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext(); ) {
				Map.Entry<String, Set<String>> entry = it.next();
				//获取当前依赖项中包含该类的记录.
				Set<String> dependenciesToClean = entry.getValue();
				//移除掉该类对其他类的依赖.
				dependenciesToClean.remove(beanName);
				if (dependenciesToClean.isEmpty()) {
					//如果某类只被该类引用,则移除该记录.
					it.remove();
				}
			}
		}
		//再从主动依赖关系中移除该类依赖的属性.
		// Remove destroyed bean's prepared dependency information.
		this.dependenciesForBeanMap.remove(beanName);
	}

	/**
	 * 暴露单例互斥体,当需要进行扩展性的单例创建,这时候继续要在该互斥体上进行同步操作,
	 * 特别需要注意的是,子类不能创建自己的互斥体,避免在惰性初始化出现死锁.
	 * <p>
	 * Exposes the singleton mutex to subclasses and external collaborators.
	 * <p>Subclasses should synchronize on the given Object if they perform
	 * any sort of extended singleton creation phase. In particular, subclasses
	 * should <i>not</i> have their own mutexes involved in singleton creation,
	 * to avoid the potential for deadlocks in lazy-init situations.
	 */
	public final Object getSingletonMutex() {
		return this.singletonObjects;
	}

}
